import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:saas_order_meal/saas_order_meal.dart';
import 'package:saas_order_meal/utils/meal_ext_utils.dart';
import 'package:saas_order_meal/viewmodel/regular_menu_contain_view_model.dart';

import '../model/order_request_data.dart';
import '../model/week_food_model.dart';
import '../net/net_response/fee_rule_data.dart';

class ApplyMealByWeekViewModel extends BaseViewModel {
  final OrderRequestData orderRequestData;
  late OrderRequestData orderData;

  var submitCode = "";

  ApplyMealByWeekViewModel(BuildContext? context,
      {required this.orderRequestData})
      : super(context) {
    orderData = orderRequestData.copyWith();
  }

  var model = WeekFoodModel();
  var msg = "";


  @override
  void onCreated() {
    super.onCreated();
    if(SaasOrderMeal.needFeeRule){
      getFeeRule();
    }
  }

  var freeMenuType = <dynamic>[];

  Future<void> getFeeRule() async {
    showLoadingDialog();
    try{
      var rule = await  model.getFeeRule(orderData.elderHumanId);
      hideDialog();
      freeMenuType = (rule.menuTypeRuleInfoList??[]).takeWhere<MenuTypeRuleInfoList>((e)=>e.moneyFlag==0).map((e)=>e.menuTypeId).toList();
      print(freeMenuType);
      // calculateTotal();
    }catch(e){
      hideDialog();
      showToast(e.toNetError());
    }
  }

  Future<void> batchSubmitOrder({int payment = 1}) async {
    var list = <SelectFoodData>[];

    showLoadingDialog(msg: "正在提交中");
    try {
      if (submitCode.isNullOrEmpty()) {
        for (var day in orderData.weekSelectFood) {
          list.addAll(day.selectFood);
        }
        var mapList = list
            .map((meal) => {
                  "elderHumanId": orderData.elderHumanId,
                  "orderDate": DateTime.now().toDateStr(
                      [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]),
                  "siteId": orderData.siteId,
                  "useAddr": orderData.siteName ?? "",
                  "useDateBet": meal.date ?? "",
                  "useDate":
                      meal.date.isNullOrEmpty() ? "" : "${meal.date} 00:00:00",
                  "totalMoney": meal.price,
                  "useType": orderData.useType,
                  "useTimeSection": meal.timeSection,
                  "menuId": orderData.menuId,
                  "useNum": 1,
                  "payment": payment,
                  "isWeek": "1",
                  "discountMoney": 0.0,
                  "orderModelType": 4,
                  "remark": "",
                  "goodsList": meal.selectFood
                      .map((e) => {
                            "goodsId": e.goodsId,
                            "num": e.number,
                            "price": e.price
                          })
                      .toList()
                })
            .toList();
        var data = await model.submitWeekOrder(
            oldId: orderData.elderHumanId, orderBeansList: mapList);
        submitCode = data['data']['orderCodeBatch'].toString();
      }
      await model.oneCardBatchPay(
          orderCodeBatch: submitCode, elderHumanId: orderData.elderHumanId);
      hideDialog();
      showCupertinoDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return WillPopScope(
                child: CupertinoAlertDialog(
                  content: Text("结算成功"),
                  actions: [
                    TextButton(
                        onPressed: () {
                          Go().pop();
                          Go().pop(result: "true");
                        },
                        child: Text('关闭'))
                  ],
                ),
                onWillPop: () => Future<bool>.value(false));
          });
    } catch (e) {
      print(e);
      hideDialog();
      showToast(e.toNetError());
    }
  }

  @override
  void dispose() {
    super.dispose();
    // orderData.weekSelectFood.clear();
  }
}
